<template>
  <div>
    <el-form label-width="100px" size="mini">
      <el-row :gutter="40">
        <el-col :span="24">
          <el-form-item label="更换明细">
            <el-table
              :loading="false"
              :data="formItem.details"
              border
              class="fixed-table-table"
              size="mini"
              max-height="240px"
            >
              <el-table-column
                label="序号"
                type="index"
                width="50"
                header-align="center"
                align="center"
              />
              <el-table-column v-for="column in insideColumns" :key="column.key" header-align="center" align="center" :label="column.title" :prop="column.key" :sortable="column.sortable">
                <template slot-scope="scope">
                  <column-render :render="column.render" :row="scope.row" :column="column" />
                </template>
              </el-table-column>
              <el-table-column label="存放位置" header-align="center" align="center" width="280px">
                <template slot-scope="scope">
                  <treeselect
                    v-model="scope.row.genghuanLocation"
                    :multiple="false"
                    :options="availableLocations"
                    placeholder="请选择位置"
                    :append-to-body="true"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="分配明细">
            <el-button size="mini" type="primary" icon="el-icon-search" style="margin-bottom: 15px;" @click="assetDialogFormVisible = true">选择资产</el-button>
            <PageableTable
              :columns="insideColumns"
              :loading="false"
              :table-height="240"
              :data="formItem.assets"
              :disable-pageable="true"
              border
              class="fixed-table-table"
            >
              <el-table-column
                label="序号"
                type="index"
                width="50"
                header-align="center"
                align="center"
              />
              <el-table-column v-for="column in assetInsideColumns" :key="column.key" header-align="center" align="center" :label="column.title" :prop="column.key" :sortable="column.sortable">
                <template slot-scope="scope">
                  <column-render :render="column.render" :row="scope.row" :column="column" />
                </template>
              </el-table-column>
              <el-table-column label="操作" header-align="center" align="center" width="80" class-name="small-padding fixed-width">
                <template slot-scope="{row}">
                  <el-button type="text" size="mini" icon="el-icon-delete" title="删除" @click="remove(row)">移除</el-button>
                </template>
              </el-table-column>
            </PageableTable>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="">
            <el-button size="mini" @click="btnCancel">取 消</el-button>
            <el-button type="primary" @click="commit">提 交</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <SelectDialog title="选择资产" :append-to-body="true" :show="assetDialogFormVisible" @on-ok="selectOk" @on-cancel="assetDialogFormVisible = false">
      <Assets
        v-if="assetDialogFormVisible"
        ref="assets"
        belongs="kj"
        :status-search-show="false"
        status-code="unused"
        :for-selection="true"
        categories="1"
        :locked="false"
      />
    </SelectDialog>
  </div>
</template>
<script>
import { confirmDetail as detail, confirmCreate as create } from '@neu/dcam-ui/api/genghuanKJ'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import PageableTable from '@neu/biz-core/components/PageableTable'
import { tree as locationTree } from '@neu/dcam-ui/api/location'
import treeselect from '@neu/biz-core/components/TreeSelect'
import Assets from '@neu/dcam-ui/views/fixedAsset/tables'
const formItem = {
  title: '', // 工单标题
  remark: '',
  workOrderNum: '',
  taskId: '',
  comprehensive: true,
  details: [],
  assets: []
}
export default {
  components: {
    PageableTable,
    treeselect,
    SelectDialog,
    Assets
  },
  props: {
    taskId: {
      required: false,
      type: String,
      default: 'NULL'
    },
    workOrderNum: {
      required: false,
      type: String,
      default: ''
    }
  },
  data() {
    return {
      assetDialogFormVisible: false,
      availableLocations: [],
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      assetInsideColumns: [
        { title: '资产名称', width: 150, key: 'name' },
        { title: '资产编号', width: 150, key: 'code' },
        { title: '资产分类', width: 300, key: 'type',
          render: (h, params) => {
            let txt = params.row.smallTypeName
            if (params.row.middleTypeName) {
              txt = params.row.middleTypeName + ' / ' + txt
            }
            if (params.row.bigTypeName) {
              txt = params.row.bigTypeName + ' / ' + txt
            }
            return h('span', txt)
          }
        },
        { title: '规格型号', width: 100, key: 'specifications' },
        { title: '序列号', width: 200, key: 'serialnumber' }
      ],
      insideColumns: [
        { title: '资产名称', width: 150, key: 'name' },
        { title: '资产编号', width: 150, key: 'code' },
        { title: '资产分类', width: 300, key: 'type',
          render: (h, params) => {
            let txt = params.row.smallTypeName
            if (params.row.middleTypeName) {
              txt = params.row.middleTypeName + ' / ' + txt
            }
            if (params.row.bigTypeName) {
              txt = params.row.bigTypeName + ' / ' + txt
            }
            return h('span', txt)
          }
        },
        { title: '规格型号', width: 100, key: 'specifications' },
        { title: '序列号', width: 200, key: 'serialnumber' },
        { title: '使用人', width: 100, key: 'managementUserName' },
        { title: '更换原因', width: 100, key: 'reason' }
      ]
    }
  },
  created() {
    this.fetch()
    // 位置树
    locationTree('kj').then(response => {
      this.availableLocations = response.data
    })
  },
  methods: {
    fetch() {
      if (this.workOrderNum !== 'NULL') {
        detail(this.workOrderNum, this.taskId).then(response => {
          this.formItem = {
            ...response.data
          }
        })
      }
    },
    commit() {
      // 配发资产不能为空
      if (this.formItem.assets.length === 0) {
        return this.$message({
          showClose: true,
          message: '分配资产明细为空，请填写资产明细后在提交!',
          type: 'error'
        })
      }
      const data = { ...this.formItem }
      const locations = this.flattenTreeDataClosure(this.availableLocations)
      data.details.forEach(l => {
        // 位置
        const location = locations.find(s => s.code === l.genghuanLocation)
        l.genghuanLocationName = location ? location.title : ''
      })

      data.workOrderNum = this.workOrderNum
      data.taskId = this.taskId
      data.assets.forEach(m => {
        m.workOrderNum = this.workOrderNum
        m.taskId = this.taskId
      })
      // ge.x 2022-04-08 增加锁屏功能
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      create(data).then(res => {
        if (res.status === 'success') {
          loading.close()
          this.$emit('cancelNewOrderForm', 'refresh')
        }
      }).catch(() => {
        loading.close()
        this.$emit('cancelNewOrderForm', 'refresh')
      })
    },
    btnCancel() {
      this.$emit('cancelNewOrderForm', 'refresh')
    },
    // 扁平化树形结构
    flattenTreeDataClosure(data) {
      const treeData = data
      const flattenData = []
      function flattenTree(data, parentKey) {
        data.forEach(ele => {
          const { title, code, children } = ele
          flattenData.push({ title, code, parentKey })
          if (children) {
            flattenTree(children, code)
          }
        })
      }
      flattenTree(treeData, null)
      return flattenData
    },
    /** 移除一条数据 */
    remove(row) {
      const i = this.formItem.assets.lastIndexOf(row)
      this.formItem.assets.splice(i, 1)
    },
    selectOk() {
      const assets = this.$refs.assets.selections
      const assetCodes = this.formItem.assets.map(a => a.code)
      const difference = assets.filter(t => {
        return !assetCodes.includes(t.code)
      })
      difference.forEach(element => {
        this.formItem.assets.push(element)
      })
      this.assetDialogFormVisible = false
    }
  }
}
</script>

<style lang="scss">
  .vue-treeselect.vue-treeselect--append-to-body {
    z-index: 9999!important;
  }
</style>
